package cwnu.sapphire.com.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import cwnu.sapphire.com.entity.LoginResult;
import cwnu.sapphire.com.entity.User;
import cwnu.sapphire.com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> list() {
        return userService.list();
    }

    @GetMapping("/{id}")
    public User getById(@PathVariable Integer id) {
        return userService.getById(id);
    }

    @PostMapping
    public boolean add(@RequestBody User user) {
        return userService.save(user);
    }

    @PutMapping
    public boolean update(@RequestBody User user) {
        return userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }
    
    /**
     * 用户登录
     * @param loginUser 包含用户名和密码的用户对象
     * @return 登录结果
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User loginUser) {
        LoginResult result = userService.login(loginUser.getUsername(), loginUser.getPassword());
        Map<String, Object> response = new HashMap<>();
        response.put("code", result.getCode());
        response.put("message", result.getMessage());
        response.put("user", result.getUser());
        return response;
    }

    // 传递一个Excel文件，将用户信息添加到数据库中
    @PostMapping("/addUsers")
    public boolean add(@RequestParam("file") MultipartFile file) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return false; // 文件为空，返回 false
        }

        String fileName = file.getOriginalFilename();
        String gradeStr = "";
        String clazzStr = "";

// 提取年级：匹配"级"字前的连续数字
        Pattern gradePattern = Pattern.compile("(\\d+)级");
        Matcher gradeMatcher = gradePattern.matcher(fileName);
        if (gradeMatcher.find()) {
            gradeStr = gradeMatcher.group(1);
        }

// 提取班级：匹配"级"和"班"之间的连续数字
        Pattern clazzPattern = Pattern.compile("级(\\d+)班");
        Matcher clazzMatcher = clazzPattern.matcher(fileName);
        if (clazzMatcher.find()) {
            clazzStr = clazzMatcher.group(1);
        }

        int grade = !gradeStr.isEmpty() ? Integer.parseInt(gradeStr) : 0;
        int clazz = !clazzStr.isEmpty() ? Integer.parseInt(clazzStr) : 0;
        List<User> users = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), User.class, new AnalysisEventListener<User>() {
            @Override
            public void invoke(User data, AnalysisContext context) {
                data.setGrade(grade); // 设置年级
                data.setClazz(clazz);  // 设置班级
                java.util.Date utilDate = new java.util.Date();
                data.setCreateTime(new Date(utilDate.getTime()));
                data.setUpdateTime(new Date(utilDate.getTime()));
                data.setDeleteFlag(0);
                users.add(data);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 所有数据读取完成后的操作
            }
        }).sheet().headRowNumber(3).doRead();

        userService.add(users); // 假设您有一个方法来批量保存用户
        return true;
    }
} 